const db = require('./db')

// 创建用户表的SQL语句
const createTableSQL = `
CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  email VARCHAR(100),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)`

// 插入测试用户的SQL语句
const insertUserSQL = `
INSERT INTO users (username, password, email) 
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE password = VALUES(password), email = VALUES(email)
`

// 初始化数据库
function initDatabase() {
  // 创建表
  db.query(createTableSQL, (err, results) => {
    if (err) {
      console.error('创建表失败:', err)
      return
    }
    console.log('用户表创建成功或已存在')
    
    // 插入测试用户
    const testUsers = [
      ['admin', 'admin123', 'admin@example.com'],
      ['test', 'test123', 'test@example.com'],
      ['user1', 'password1', 'user1@example.com']
    ]
    
    testUsers.forEach(([username, password, email]) => {
      db.query(insertUserSQL, [username, password, email], (err, results) => {
        if (err) {
          console.error(`插入用户 ${username} 失败:`, err)
        } else {
          console.log(`用户 ${username} 创建成功`)
        }
      })
    })
  })
}

// 执行初始化
initDatabase()

// 5秒后关闭连接
setTimeout(() => {
  db.end()
  console.log('数据库连接已关闭')
}, 5000) 